﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;

namespace Wild2.Models.Auth
{
    public class RegisterOnSite
    {
        public static readonly Regex _reg = new Regex("[^А-Яа-яA-Za-z-_\\.0-9]+");
        public static readonly Regex _regEn = new Regex("[A-Za-z]+");
        public static readonly Regex _regRu = new Regex("[А-Яа-я]+");

        public static bool CheckCode(String code)
        {
            if (code == "admin") return true;
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT COUNT(ID) FROM [Invites] WHERE ([Code] = @Code) AND ([Kogo] IS NULL)", conn))
                {
                    cmd.Parameters.Add("@Code", System.Data.SqlDbType.NVarChar, 50).Value = code;
                    cmd.Connection.Open();
                    if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) return true;
                    cmd.Connection.Close();
                }
            }
            return false;
        }

        public static bool UpdateCode(String code, Int32 UserIDKogo)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("UPDATE [Invites] SET [Kogo] = @Kogo WHERE ([Code] = @Code) AND ([Kogo] IS NULL)", conn))
                {
                    cmd.Parameters.Add("@Code", System.Data.SqlDbType.NVarChar, 50).Value = code;
                    cmd.Parameters.Add("@Kogo", System.Data.SqlDbType.Int).Value = UserIDKogo;
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                }
            }
            return false;
        }

        public static Int32? Register(String userName, String password)
        {
            Int32? uid = null;
            String version = "pda";
            Object v = HttpContext.Current.Session[Wild2.Models.Constants.SessionConstants.VERSION];
            if (v != null) version = v.ToString();
            //Проверяем не попадает ли имя в список занятых имен
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectStatistic"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT COUNT(ID) FROM [Names] WHERE ([Name] = @Name)", conn))
                {
                    cmd.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 20).Value = userName;
                    cmd.Connection.Open();
                    if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) return null;
                    cmd.Connection.Close();
                }
            }
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT COUNT(ID) FROM [Users] WHERE ([Nick] = @Name)", conn))
                {
                    cmd.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 20).Value = userName;
                    cmd.Connection.Open();
                    if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) return null;
                    cmd.Connection.Close();
                }
            }
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
            {
                //Int32? developer = null;
                //if (HttpContext.Current.Session[Wild2.Models.Constants.SessionConstants.DEV] != null) developer = Convert.ToInt32(HttpContext.Current.Session[Wild2.Models.Constants.SessionConstants.DEV]);
                //else if (ConfigurationManager.AppSettings["developer"] != null) developer = Convert.ToInt32(ConfigurationManager.AppSettings["developer"]);

                using (SqlCommand cmd = new SqlCommand("INSERT INTO Users([Nick], [Password], [skin]) VALUES (@Nick, @Pass, @Skin); SELECT SCOPE_IDENTITY() as ID", conn))
                {
                    cmd.Parameters.Add("@Nick", System.Data.SqlDbType.NVarChar, 20).Value = userName;
                    cmd.Parameters.Add("@Pass", System.Data.SqlDbType.NVarChar, 50).Value = MD5Helper.GetMd5Hash(password);
                    cmd.Parameters.Add("@Skin", System.Data.SqlDbType.NVarChar, 10).Value = version;
                    //if (developer.HasValue) cmd.Parameters.Add("@D", System.Data.SqlDbType.Int).Value = developer.Value;
                    //else cmd.Parameters.Add("@D", System.Data.SqlDbType.Int).Value = DBNull.Value;
                    cmd.Connection.Open();
                    try
                    {
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                uid = Convert.ToInt32(reader["ID"]);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //Такой юзер уже есть
                        return null;
                    }
                    cmd.Connection.Close();
                }
                if (uid.HasValue)
                {
                    String privateKey;
                    using (SqlCommand cmd = new SqlCommand("SELECT [PrivateKey] FROM Users WHERE (ID = @UID)", conn))
                    {
                        cmd.Parameters.Add("@UID", System.Data.SqlDbType.Int).Value = uid.Value;
                        cmd.Connection.Open();
                        privateKey = cmd.ExecuteScalar().ToString();
                        cmd.Connection.Close();
                    }
                    HttpContext.Current.Session[Wild2.Models.Constants.SessionConstants.USERID] = uid.Value;
                    UserIP.UserIPLog(uid.Value);
                    if (!String.IsNullOrEmpty(privateKey))
                    {
                        HttpCookie cookie = new HttpCookie("PrivateKey");
                        cookie.Value = privateKey;
                        cookie.Expires = DateTime.Now.AddMonths(6);
                        HttpContext.Current.Response.Cookies.Add(cookie);
                    }
                }
            }
            return uid;
        }
    }
}